﻿using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using MongoDB.Bson;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace component
{
    internal class Commons
    {
        public string savePath;
        public static string message1;
        public static ElementSet elements;
        public static ExternalCommandData commandData;
        public static string GetMD5HashFromFile(string fileName)
        {
            try
            {
                FileStream file = new FileStream(fileName, FileMode.Open);
                MD5 md5 = new MD5CryptoServiceProvider();
                byte[] retVal = md5.ComputeHash(file);
                file.Close();
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < retVal.Length; i++)
                {
                    sb.Append(retVal[i].ToString("x2"));
                }
                return sb.ToString();
            }
            catch (Exception)
            {
                throw new Exception("GetMD5HashFromFile() fail,error:");
            }
        }
        //
        public static Result Familyfy(ExternalCommandData commandData, string filePath)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument uidoc = uiapp.ActiveUIDocument;
            Document familyDoc = uidoc.Document;
            Family family = null;
            using (Transaction tran = new Transaction(familyDoc, "11"))
            {
                tran.Start();
                familyDoc.LoadFamily(filePath, out family);
                tran.Commit();
            }
            if (family != null)
            {
                var symbol = familyDoc.GetElement(family.GetFamilySymbolIds().FirstOrDefault()) as FamilySymbol;
                uidoc.PromptForFamilyInstancePlacement(symbol);
            }
            return Result.Succeeded;
        }
        //数据库
        private static void Insert(string json)
        {
            string connStr = "mongodb://127.0.0.1:27017";
            //2.创建连接MongoClient实例实际上代表了一个到数据库的连接池，即使有多个线程，也只需要一个MongoClient类的实例
            var client = new MongoClient(connStr);
            //3.使用client的GetDatabase方法获取数据库，即使该数据库不存在，也会自动创建；
            IMongoDatabase db = client.GetDatabase("revit_model");
            //4.获取数据集 collection；BsonDocument是在数据没有预先定义好的情况下使用的。
            IMongoCollection<BsonDocument> collection = db.GetCollection<BsonDocument>("family");
            BsonDocument document = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>(json);
            collection.InsertOne(document);

        }
        //读取族文件数据，传给数据库
        //filePath：文件路径
        public static Result ExactFamily(ExternalCommandData commandData, string filePath)
        {
            Family family = null;
            Document doc = commandData.Application.ActiveUIDocument.Document;

            Transaction tran = new Transaction(doc);
            tran.Start("载入族");
            doc.LoadFamily(filePath, out family);
            tran.Commit();
            //Get_FamilySymbol(family);  
            Element element = family as Element;
            TaskDialog.Show("family Name:", family + "");
            //string name = "{\"" +family.Name +"\" : \" \"}";
            //getSymbolpara();//获取族类型参数
            //ShowAllBuildinPara();//将族类型信息参数转成table表格
            // 族文件数据信息-->数据库
            string family_json = "";
            //try
            //{
                string connStr = "mongodb://127.0.0.1:27017";
                //2.创建连接MongoClient实例实际上代表了一个到数据库的连接池，即使有多个线程，也只需要一个MongoClient类的实例
                var client = new MongoClient(connStr);
                //3.使用client的GetDatabase方法获取数据库，即使该数据库不存在，也会自动创建；
                IMongoDatabase db = client.GetDatabase("revit_model");
                //4.获取数据集 collection；BsonDocument是在数据没有预先定义好的情况下使用的。
                IMongoCollection<BsonDocument> collection = db.GetCollection<BsonDocument>("family");
                //BsonDocument document = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>(name);
                // 获得族管理器
                FamilyManager familyMgr = doc.FamilyManager;
                FamilyType currType = familyMgr.CurrentType;
                if (currType != null)// 当前族类型可能为空，故需进行空检查
                {   
                    FamilyParameterSet familyParamSet = familyMgr.Parameters;
                    ISet<ElementId> familySymbolIds = family.GetFamilySymbolIds();
                    foreach (ElementId id in familySymbolIds)
                    {
                        FamilySymbol familySymbol = family.Document.GetElement(id) as FamilySymbol;
                        family_json += "{ \" Name \": "  + "\"" +familySymbol.Name + "\",";
                        foreach (FamilyParameter param in familyParamSet)
                        {

                            if (param.Definition.ParameterType == ParameterType.Length)//可找到对应参数值
                            {
                                double oneValueOfFamilySymbol = currType.AsDouble(param).Value;
                                double unitByMeter = UnitUtils.Convert(oneValueOfFamilySymbol, DisplayUnitType.DUT_DECIMAL_FEET, DisplayUnitType.DUT_METERS);
                                family_json +="\"" + param.Definition.Name +"\" "+ ":\"" + unitByMeter + "\" ,";
                            }
                            else//找不到对应参数值
                            {
                                family_json += "\"" + param.Definition.Name + "\":\"" + " - " + "\",";
                            }
                        }
                        family_json += "\"" + "" + "\":\"" + " " + "\"}";
                       
                        //BsonDocument document1 = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>(family_json);
                        //StreamWriter sw = new StreamWriter("F:\\1.txt", false);
                        //sw.WriteLine(family_json);
                        //sw.Close();
                        //TaskDialog.Show("Result", "保存成功");
                        //MessageBox.Show(family_json, "信息");
                    }
                }
            
            //catch (Exception ex)
            //{
            //    TaskDialog.Show("Revit", ex.Message);

            //}
            //string json_format_string = Newtonsoft.Json.JsonConvert.SerializeObject(info);
            //弹窗展示json格式参数信息
            //TaskDialog.Show("Result", json_format_string);
            return Result.Succeeded;
        }
    }
}
